import axios from 'axios';
import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';
import Vue from 'vue';
const now = new Date();

const userInfo = JSON.parse(localStorage.getItem('userInfo'));
const currentUser = userInfo?userInfo.managerName:null
const state = {
    admins: [],
    sessions: {},
    currentSessionId:{},
    currentUser:currentUser,
    filterKey: '',
    stompClient: null,
    idDot:{}
}
const getters = {

}
const mutations = {
    changeCurrentSessionId(state, id) {
        state.currentSessionId = id;
        state.idDot[state.currentUser + '#'+state.currentSessionId.managerName]=false

    },
    addMessage(state, msg) {
       
      
      let mss =  state.sessions[currentUser + '#' + msg.to]
        if(!mss){
            state.sessions[currentUser + '#' + msg.to] = []
        }
        state.sessions[currentUser + '#' + msg.to].push({
            content:msg.content,
            date: new Date(),
            self:!msg.notSelf
        })
        console.log('state.sessions',state.sessions)
    },
    INIT_ADMINS(state, data) {
        state.admins = data
    },
    INIT_DATA (state) {
      let data = localStorage.getItem('vue-chat-session');
      //console.log(data)
      if (data) {
        state.sessions = JSON.parse(data);
      }
    }
}

const actions = {
    connect(context) {
        // context.state.stomp = Stomp.over(new SockJS('ws/cinema'))
        // let token = localStorage.getItem('token')
        // context.state.stomp.connect({'token':token},success=>{
        //     context.state.stomp.subscribe('user/queue/chat',msg=>{
        //         console.log(msg.body)
        //     })
        // })
        // const socket = new SockJS('http://localhost:9999/ws/ep');
        let token = localStorage.getItem('token');
        console.log("connect token",token)
        if(context.state.stompClient){
          context.state.stompClient.deactivate();
          console.log("ddddddddddddddddddddddddddddddddddddddddddd")
        }

        context.state.stompClient = new Client({
          brokerURL: `ws://localhost:9999/ws?token=${encodeURIComponent(token)}`,
          reconnectDelay: 5000,
          connectHeaders: {
            'token': `${token}` // 自定义 Header
          },
          onConnect: () => {
            // 订阅公共频道
            // stompClient.subscribe('/chat', (response) => {
            //     console.log("+++++++++++++++++",response)
            //   receivedMessage.value = response.body;
            // });
            context.state.stompClient.subscribe('/user/queue/chat', function(response){
                console.log('msg',response.body)
                let body = response.body
                let receivedMessage = JSON.parse(body)
                receivedMessage.notSelf = true
                receivedMessage.to = receivedMessage.from
                context.commit('addMessage',receivedMessage)

                if(!context.state.currentSessionId.managerName || receivedMessage.from != context.state.currentSessionId.managerName){
                  context.state.idDot[state.currentUser + '#'+receivedMessage.from]=true
                }
                console.log('idot',state.idDot)


              });
            // 订阅私信频道（可选）
            // stompClient.subscribe('/user/queue/private', (response) => {
            //   console.log('收到私信:', response.body);
            // });
          },
          onDisconnect: () => {
            console.log('连接断开');
        },
        onWebSocketClose: (event) => {
            console.log('WebSocket 关闭:', event);
        },
        debug: (str) => {
            console.log('STOMP 调试:', str); // 打印底层协议交互
        },
        onStompError: (frame) => {
            console.error('STOMP 错误:', frame.headers.message);
          },
          onmessage:(msg)=>{
            console.log('+++++++++++',msg)
          }
        });
        context.state.stompClient.activate();
    },
    async initData(context) {
        context.commit('INIT_DATA')
        const { data: res } = await axios.get(
            "/manager/getAll"
        );
        if (res.code != 200) {
        } else {
            context.commit('INIT_ADMINS', res.data)
        }
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}